package com.mjk.common.core.rmq.mq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;

public class CategoryListenerContainer implements MessageListener{
	private static final Logger logger = LoggerFactory.getLogger(CategoryListenerContainer.class);

    private final int priority;

    private final SimpleMessageListenerContainer container;

    private final MessageHander messageHander;

    public CategoryListenerContainer(int priority, RmqChannel channel, String[] queueName, MessageHander messageHander, int prefetchCount) {
        this.priority = priority;
        this.container = new SimpleMessageListenerContainer(channel.getConnectionFactory());
       
        this.messageHander = messageHander;
        this.container.setPrefetchCount(prefetchCount);
        this.container.setConcurrentConsumers(1);
        this.container.setAutoDeclare(false);
        this.container.setMissingQueuesFatal(true);
        this.container.setDeclarationRetries(0);
        this.container.setFailedDeclarationRetryInterval(-1);
        this.container.setQueueNames(queueName);
        MessageListenerAdapter adapter = new MessageListenerAdapter(this);
        this.container.setMessageListener(adapter);
    }

    public void start() {
        if (!this.container.isRunning()) {
            this.container.start();
            logger.debug("priority {} queue listener container started", priority);
        }
    }



	@Override
	public void onMessage(Message message) {
		this.messageHander.handleMessage(message, priority);
	}
}
